<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<title>作业通知-教师-云校通</title>
<jsp:include page="/WEB-INF/page/common/_header.jsp"></jsp:include>
<body ontouchstart>
	<div class="weui_tab tab-bottom">
		<div class="weui_tab_bd">
			<div class="weui_cells weui_cells_form" style="margin: 0;">
	            <div class="weui_cell">
	                <div class="weui_cell_bd weui_cell_primary">
	                    <textarea id="content" class="weui_textarea" placeholder="发什么作业呢，容我好好想想……" rows="5"></textarea>
	                </div>
	            </div>
	            <div class="weui_uploader">
                    <div class="weui_uploader_bd">
                        <ul class="weui_uploader_files img-click" id="img1">
                        </ul>
                        <div class="weui_uploader_input_wrp" id="filePicker" style="margin-bottom: 20px; margin-left: 15px; width: 60px; height: 60px; border-radius: 5px;">
                           
                        </div>
                    </div>
                </div>
	        </div>
	        <div class="weui_cells weui_cells_access" id="xs_div">
	            <a class="weui_cell" href="javascript:">
	                <div class="weui_cell_hd"><img src="<%=basePath %>/images/fasongduixiang@3x.png" alt="" style="width:20px;margin-right:10px;display:block"></div>
	                <div class="weui_cell_bd weui_cell_primary">
	                    <p>班级</p>
	                </div>
	                <div class="weui_cell_ft">请选择</div>
	            </a>
	        </div>
	        <div class="weui_btn_area">
		        <a href="javascript:" class="weui_btn bg-blue" id="album-submit">确认发送</a>
		    </div>
		    <!-- 今日通知 start -->
		    <div class="weui_cells">
			    <div class="weui_cell lblue tz-history-title" style="background-color: #fff;">
	                <div class="weui_cell_bd weui_cell_primary">
	                    <p class="bold pr">今日已发通知 <a href="<%=basePath %>/ls/notices/sender/list?nt=${noticeType}" class="f-blue">历史记录</a></p>
	                </div>
	            </div>
		        <div class="ly-lsjl">
					<div class="weui_panel weui_panel_access">
			            <div class="weui_panel_bd" id="noticeList">
			                
			            </div>
			        </div>
				</div> 
			</div>
			<!-- 今日通知 end -->
			<script id="notice-table-template" type="text/x-handlebars-template">
				{{#each rows}}
				<a href="<%=basePath %>${user.currUrl}/notices/detail/{{id}}" style="display: block;color: #000;">
					<div class="weui_cell moments__post" style="padding: 10px 5px;">
			          <div class="weui_media_bd">
			            <p class="weui_media_desc" style="color:#999;">{{dateFormat createTime}}</p>
			            <!-- post内容 -->
			            <p class="paragraph" style="padding-top: 10px;">{{content}}</p>
			            <!-- 伸张链接 -->
			            <a class="paragraphExtender">全文</a>
			            <!-- 相册 -->
						<div class="thumbnails1 img-click">
							{{#each attachList}}
					           <div class="thumbnail1">
									<img onclick="imgClick(this)" class="img-max" src="${config.imgUrl}{{attachmentUrl}}">
							   </div>
							{{/each}}
					    </div>
			          </div>
					</div>
				</a>
			{{/each}}
		</script>
		</div>
  </div>
  
  <!-- 学生组织架构 start -->
	<div id="xs_div_box" class="weui_tab tab-bottom" style="display:none; z-index:600; background-color: #f8f8f8;">
		<div class="weui_tab_bd">
	        <div class="weui-header bg-blue"> 
	        	<div class="weui-header-left" id="teacherBack"> <a class="icon icon-109 f-white">取消</a>  </div>
				<h1 class="weui-header-title">我的班级列表</h1>
			</div>
	        <!--下拉选择-->
	        <div class="page-bd">  
	          <ul id="classList">
	     	  </ul>
	    	</div>
	    	<script id="class-table-template" type="text/x-handlebars-template">
	    		{{#each list}}
	    			<li class="list1" style="margin: 0;">
           				<div class="weui_cells" style="margin: 0;">
                    		<div class="weui_cell" style="padding: 20px 15px;">
								<div class="weui_cell_hd list_c2" style="margin-right: 10px;">
									<label class="weui_cells_checkbox weui_check_label" for="{{grade}}_{{clazz}}">
										<div class="weui_cell_hd">
											<input type="checkbox" class="weui_check" value="{{grade}}_{{clazz}}" id="{{grade}}_{{clazz}}">
			        						<i class="weui_icon_checked icon-35"></i>
										</div>
									</label>
								</div>
								<div class="weui_cell_bd weui_cell_primary">
									<p>{{gradeText}}（{{clazz}}）班</p>
								</div>
							</div>
						</div>
	            	</li>
	            {{/each}}
			</script>
	       </div>
	   		<!--End下拉选择-->
			<div class="weui_tabbar ">
				<div class="fsdx_tabbar">
		            <span class="left">
						<div class="weui-flex">
		                	<span style="margin-top: 13px;margin-left: 0px;">
							<label class="weui_cells_checkbox weui_check_label" for="classAll">
								<div class="weui_cell_hd">
									<input type="checkbox" class="weui_check" id="classAll">
					        		<i class="weui_icon_checked"></i>
								</div>
							</label>
							</span>
		                   	<p class="weui-flex-item"> 全选</p>
		                </div>
					</span>
		            <span class="left">班级：<label id="classCount">0</label></span>
		            <span class="right" id="classSure"><a href="javascript:">确定</a></span>
		        </div>
			</div>
		</div>
	</div>
	
  <jsp:include page="/WEB-INF/page/common/_footer.jsp"></jsp:include>
  <script type="text/javascript">
  	var classData = {};
  	$(function() {
  		initHandingAttach();
  		//初始化班级架构
		loadClass();
		//今日通知
		loadTodayNotice();
		$("#album-submit").click(function() {
			noticeSubmit();
		});
		$("#teacherBack").click(function() {
			$("#xs_div_box").hide();
			$("#classCount").html(0);
			$("#classAll")[0].checked = false;
			$(".weui_cell_ft").html("请选择");
			loadClassHtml(classData);
		});
		//学生组织架构弹出
      	$("#xs_div").click(function() {
      		$("#xs_div_box").show();
      		$(".list_c2 input").change(function() {
      			var total = $("#classList").find(".list_c2 input").length;
				var length = $("#classList").find(".list_c2 input:checked").length;
				if(total == length) $("#classAll")[0].checked = true;
				else $("#classAll")[0].checked = false;
				$("#classCount").html(length);
      		});
      		//班级全选
	      	$("#classAll").click(function() {
	      		if(this.checked) {
	      			var list = $("#classList").find("input");
	      			list.each(function(i, v){
						v.checked = true;
					});
	      		}else {
	      			var list = $("#classList").find("input:checked");
	      			list.each(function(i, v){
						v.checked = false;
					});
	      		}
	      		var length = $("#classList").find("input:checked").length;
  				$("#classCount").html(length);
	      	})
      		$("#classSure").click(function() {
				$("#xs_div_box").hide();
				var length = $("#classList").find("input:checked").length;
				if(length > 0) $(".weui_cell_ft").html("已选择" + length + "个班级");
				else $(".weui_cell_ft").html("请选择");
      		})
      	});
  	});
  	function loadClass() {
		$.ajax({
	 		url : basePath + "/myClass",
	 		type : "post",
	 		dataType : "json",
	 		async : false,
	 		success : function(data) {
	 			if(data != null && data.length > 0) {
	 				classData.list = data;
	 				loadClassHtml(classData);
	 			}
	 		}, error:function(){
	 			alert("查询异常");
   			}
	 	});
	}
	function loadClassHtml(classData) {
		var myTemplate = Handlebars.compile($("#class-table-template").html());
		
		Handlebars.registerHelper("equal", function(v1,v2,options) {
    		if(v1 == v2) {
    			//满足添加继续执行
    			return options.fn(this);
    		}else {
    			//不满足条件执行{{else}}部分
    			return options.inverse(this);
    		}
    	});
		$('#classList').html(myTemplate(classData));
	}
	
	/* document.querySelector('#imgid').onchange = function(e) {
		var files = e.target.files;
		var len = files.length;
		for (var i=0; i < len; i++) {
			lrz(files[i], {
				width:1080
			})
			.then(function (rst) {
				var xhr = new XMLHttpRequest();
	            xhr.open('POST', basePath + "/ls/attchment/upload/lrz");
	            xhr.onload = function () {
	                if (xhr.status === 200) {
	                	$('#img1').append('<li class="weui_uploader_file" style="background-image:url('+rst.base64+')"></li>');
	                }
	            };
	            xhr.onerror = function () {
	            	alert("上传异常");
	            };
	            xhr.upload.onprogress = function (e) {
	                // 上传进度
	                var percentComplete = ((e.loaded / e.total) || 0) * 100;
	            };
	            // 添加参数
	            rst.formData.append('attachmentName', rst.origin.name);
	            rst.formData.append('attachmentSize', rst.fileLen);
	            rst.formData.append('baseData', rst.base64);
	            rst.formData.append('attachmentType', "image");
	            rst.formData.append('relationType', "${relationType}");
	            // 触发上传
	            xhr.send(rst.formData);
	            return rst;
			})
	        .always(function () {
	            // 不管是成功失败，都会执行
	        });
			;
		}
	} */
	
	//拍照或从手机相册中选图接口
    $('#filePicker').on('click', function () {
        wx.chooseImage({
            count: 9,
            needResult: 1,
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
           		var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
           		wxuploadImage(localIds);
            },
            fail: function (res) {
                alterShowMessage("操作提示", JSON.stringify(res), "1", "确定", "", "", "");
            }

        });
    });
	function wxuploadImage(localIds) {  
		var localId = localIds.pop();
        wx.uploadImage({  
            localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得  
            isShowProgressTips: 1, // 默认为1，显示进度提示  
            success: function (res) {  
                mediaId = res.serverId; // 返回图片的服务器端ID
                wechatMediaDownload(mediaId);
                if(localIds.length > 0){
                	wxuploadImage(localIds);
                }
            },  
            fail: function (error) {  
                alert(Json.stringify(error));  
            }  
        });
   }  
   function wechatMediaDownload(mediaId) {
	   	var params = {};
	   	params.mediaId = mediaId;
        params.attachmentType = "image";
        params.noticeType = parseInt("${noticeType}");
        params.relationType = "${relationType}";
        $.ajax({
	 		url : basePath + "/ls/attchment/upload/wx",
	 		type : "post",
	 		data : params,
	 		dataType : "json",
	 		async : false,
	 		success : function(data) {
	 			if(data.code != '000') {
	 				$.toast(data.msg, "cancel");
	 			}else {
	 				$('#img1').append('<li class="weui_uploader_file" data-id="'+data.data.id+'" style="margin-right:0;margin-bottom:16px;position: relative;"><div class="img-del" onclick="imgDel(this)"><span class="icon icon-26"></span></div><img onclick="imgClick(this)" src="'+ imgUrl + data.data.attachmentUrl +'"/></li>'); 
	 			}
	 		}, error:function(){
	 			alert("上传异常");
      			}
	 	});
   }
	
	function initHandingAttach() {
		$.ajax({
	 		url : basePath + "/ls/attchment/handing",
	 		type : "post",
	 		dataType : "json",
	 		data: {
	 			relationType: "${relationType}"
	 		},
	 		async : false,
	 		success : function(data) {
	 			if(data != null && data.length > 0) {
	 				for(var itm in data) {
	 					if(data[itm].attachmentType == 'image') {
	 						$('#img1').append('<li class="weui_uploader_file" data-id="'+data[itm].id+'" style="margin-right:0;margin-bottom:16px;position: relative;"><div class="img-del" onclick="imgDel(this)"><span class="icon icon-26"></span></div><img onclick="imgClick(this)" src="'+ imgUrl + data[itm].attachmentUrl +'"/></li>');          
	 					}
	 				}
	 			}
	 		}, error:function(){
	 			alert("查询异常");
   			}
	 	});
	}
	function noticeSubmit() {
		var content = $("#content").val();
		if(content.trim().length==0){
			alert("请输入通知内容");
			return;
		}
		if(content.length > 2000) {
			alert("您输入的内容过长，不能超过2000字符");
			return;
		}
		if($(".weui_cell_ft").html() == "请选择") {
			alert("请选择发送对象");
			return;
		}
		var ids = new Array();
		var list = $("#classList").find(".list1 input:checked");
		list.each(function(i, v) {
			ids.push($(v).val());
		});
		$.ajax({
	 		url : basePath + "/ls/notice/create",
	 		type : "post",
	 		data : {
	 			ids: ids.toString(),
	 			content: content,
	 			noticeType: parseInt("${noticeType}")
	 		},
	 		dataType : "json",
	 		async : false,
	 		success : function(data) {
	 			if(data.code == '000') {
	 				$.toast("作业通知创建成功");
	 				$("#content").val(null);
	 				$("#img1").html("");
	 				$("#teacherBack").trigger("click");
	 				loadTodayNotice();
	 			}else{
	 				$.toast(data.msg, "cancel");
	 			}
	 		}, error:function(){
	 			$.toast("提交异常", "cancel");
   			}
	 	});
	}
   function loadTodayNotice() {
	   $.ajax({
         	url : basePath + "/ls/notices/sender/today",
 	 		type : "post",
 	 		dataType : "json",
 	 		data : {
 	 			noticeType: "${noticeType}"
 	 		},
            success: function(data){
            	var result = {};
            	result.rows = data;
           	  	loadNoticeHtml(result);
           	  	paragraph();
             },
             error: function(xhr, type){
                 
             }
         });
   }
   function loadNoticeHtml(data){
 		if(data.rows.length > 0) {
 			var myTemplate = Handlebars.compile($("#notice-table-template").html());
 			Handlebars.registerHelper("equal", function(v1,v2,options) {
 				if(v1 == v2) {
 					//满足添加继续执行
 					return options.fn(this);
 				}else {
 					//不满足条件执行{{else}}部分
 					return options.inverse(this);
 				}
 			});
 			Handlebars.registerHelper("dateFormat", function(v1) {
 				return getTime(v1, "yyyy-MM-dd hh:mm:ss");
 			});
 			$('#noticeList').html(myTemplate(data));
 		}
	}
	function paragraph() {
		$("#noticeList .moments__post").each(function(i, v) {
			//定义文本
			const paragraph = $($(this).find('.paragraph'));
			const paragraphText = paragraph.text();
			const paragraphLength = paragraph.text().length;
			//定义文章长度
			const maxParagraphLength = 80;
			//定义全文按钮
			const paragraphExtender = $($(this).find('.paragraphExtender'));
			var toggleFullParagraph = false;
			
			//定义全文按钮
			if (paragraphLength < maxParagraphLength) {
			  paragraphExtender.hide();
			} else {
			  paragraph.html(paragraphText.substring(0, maxParagraphLength) + '...');
			  paragraphExtender.click(function(){
			    if (toggleFullParagraph) {
			      toggleFullParagraph = false;
			      paragraphExtender.html('全文');
			      paragraph.html(paragraphText.substring(0, maxParagraphLength) + '...');
			    } else {
			      toggleFullParagraph = true;
			      paragraphExtender.html('收起');
			      paragraph.html(paragraphText);
			    }
			  });
			};
		});
   }
   
</script>
</body>
</html>